#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor.AddressableAssets.Settings;
using UnityEditor.AddressableAssets;
using UnityEditor.AddressableAssets.Settings.GroupSchemas;
using UnityEditor.AddressableAssets.Build;
using System;
using Newtonsoft.Json.Linq;

namespace OA
{
    public partial class CallDlcAsset : EditorWindow
    {
        private List<DLCAssetInfo> _dlcAssets = new List<DLCAssetInfo>();
        private Dictionary<string, bool> _dlcSelection = new Dictionary<string, bool>();
        private Vector2 _scrollPosition;
        private string _searchText = "";
        private bool _isBuilding = false;
        private BuildTarget _selectedTarget;

        /// <summary>
        /// DLCAsset信息类
        /// </summary>
        private class DLCAssetInfo
        {
            public string DLCName { get; set; }
            public string DLCVersion { get; set; }
            public string DLCDesc { get; set; }
            public string AssetPath { get; set; }
            public string SourceType { get; set; } // "Main Project" 或 "Package"
            public List<AddressableAssetGroup> Groups { get; set; } = new List<AddressableAssetGroup>();
        }

        /// <summary>
        /// 显示编辑器窗口
        /// </summary>
        [MenuItem("OA/基于DLCAsset获取(构建)资源")]
        public static void ShowWindow()
        {
            GetWindow<CallDlcAsset>("基于DLCAsset获取(构建)资源");
        }

        private void OnEnable()
        {
            RefreshDLCAssets();
            _selectedTarget = EditorUserBuildSettings.activeBuildTarget;
        }

        private void OnGUI()
        {
            // 刷新按钮
            if (GUILayout.Button("刷新DLCAsset列表", GUILayout.Height(20)))
            {
                RefreshDLCAssets();
            }

            EditorGUILayout.Space();

            // 搜索框
            EditorGUILayout.BeginHorizontal();
            _searchText = EditorGUILayout.TextField("搜索DLC：", _searchText);
            if (GUILayout.Button("清空", GUILayout.Width(50)))
            {
                _searchText = "";
            }
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.Space();

            // DLC列表
            EditorGUILayout.LabelField("选择要构建的DLC：", EditorStyles.label);

            if (_dlcAssets.Count == 0)
            {
                EditorGUILayout.HelpBox("没有找到任何DLCAsset文件。", MessageType.Info);
            }
            else
            {
                _scrollPosition = EditorGUILayout.BeginScrollView(_scrollPosition, GUILayout.Height(400));

                // 按来源类型分组显示
                var mainProjectDLCs = _dlcAssets.Where(d => d.SourceType == "Main Project").ToList();
                var packageDLCs = _dlcAssets.Where(d => d.SourceType == "Package").ToList();

                // 显示主工程DLC
                if (mainProjectDLCs.Count > 0)
                {
                    EditorGUILayout.LabelField("主工程DLC", EditorStyles.boldLabel);
                    DisplayDLCList(mainProjectDLCs);
                    EditorGUILayout.Space();
                }

                // 显示包DLC
                if (packageDLCs.Count > 0)
                {
                    EditorGUILayout.LabelField("包DLC", EditorStyles.boldLabel);
                    DisplayDLCList(packageDLCs);
                }

                EditorGUILayout.EndScrollView();
            }

            // 选择按钮组
            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("全选"))
            {
                foreach (var dlc in _dlcAssets) _dlcSelection[dlc.DLCName] = true;
            }
            if (GUILayout.Button("全不选"))
            {
                foreach (var dlc in _dlcAssets) _dlcSelection[dlc.DLCName] = false;
            }
            if (GUILayout.Button("选中搜索的DLC"))
            {
                SelectSearchedDLCs(true);
            }
            if (GUILayout.Button("取消搜索的DLC"))
            {
                SelectSearchedDLCs(false);
            }
            EditorGUILayout.EndHorizontal();

            // 已选中计数
            int selectedCount = _dlcSelection.Values.Count(v => v);
            EditorGUILayout.LabelField($"已选中：{selectedCount}/{_dlcAssets.Count} 个DLC");

            EditorGUILayout.Space();
            // EditorGUILayout.LabelField("构建设置", EditorStyles.boldLabel);

            // 构建平台
            // _selectedTarget = (BuildTarget)EditorGUILayout.EnumPopup("构建平台：", _selectedTarget);

            EditorGUILayout.Space();
            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("同步脚本", GUILayout.Height(30)))
            {
                BuildPrograms(_dlcAssets, _dlcSelection);
            }
            if (GUILayout.Button("同步脚本(删除所有文件)", GUILayout.Height(30)))
            {
                BuildPrograms(_dlcAssets, _dlcSelection, true);
            }
            EditorGUILayout.EndHorizontal();

            if (GUILayout.Button("编译", GUILayout.Height(30)))
            {
                CompileDlcWithCommandLine(_dlcAssets, _dlcSelection);
            }

            if (GUILayout.Button("修复AddressableSettings", GUILayout.Height(30)))
            {
                AddressableSerializationTrigger.TriggerAllGroupsSerialization();
            }
            // 构建按钮
            GUI.enabled = !_isBuilding && selectedCount > 0;
            if (GUILayout.Button(_isBuilding ? "构建中..." : "构建选中的DLC", GUILayout.Height(30)))
            {
                BuildSelectedDLCs();
            }
            GUI.enabled = true;

            if (_isBuilding)
            {
                EditorGUILayout.HelpBox("构建进行中，请等待...", MessageType.Info);
            }
        }

        /// <summary>
        /// 显示DLC列表
        /// </summary>
        private void DisplayDLCList(List<DLCAssetInfo> dlcList)
        {
            var filteredDLCs = dlcList;
            if (!string.IsNullOrEmpty(_searchText))
            {
                filteredDLCs = dlcList
                    .Where(d => d.DLCName.ToLower().Contains(_searchText.ToLower()) ||
                               d.DLCDesc.ToLower().Contains(_searchText.ToLower()))
                    .ToList();
            }

            foreach (var dlc in filteredDLCs)
            {
                EditorGUILayout.BeginVertical(GUI.skin.box);

                EditorGUILayout.BeginHorizontal();
                GUI.color = _dlcSelection[dlc.DLCName] ? Color.green : Color.white;

                _dlcSelection[dlc.DLCName] = EditorGUILayout.ToggleLeft(
                    dlc.DLCName,
                    _dlcSelection[dlc.DLCName],
                    GUILayout.Width(150)
                );

                GUI.color = Color.white;

                EditorGUILayout.LabelField($"({dlc.Groups.Count} 个组)", GUILayout.Width(80));
                EditorGUILayout.EndHorizontal();

                // 显示版本号输入框
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.LabelField("版本号:", GUILayout.Width(60));
                dlc.DLCVersion = EditorGUILayout.TextField(dlc.DLCVersion);
                if (GUILayout.Button("版本号++", GUILayout.Width(80)))
                    dlc.DLCVersion = IncrementVersion(dlc.DLCVersion);
                EditorGUILayout.EndHorizontal();

                // 显示描述输入框
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.LabelField("描述:", GUILayout.Width(60));
                dlc.DLCDesc = EditorGUILayout.TextField(dlc.DLCDesc, GUILayout.ExpandWidth(true));
                EditorGUILayout.EndHorizontal();

                EditorGUILayout.EndVertical();
                EditorGUILayout.Space();
            }
        }

        /// <summary>
        /// 递增版本号的最后一个数字
        /// </summary>
        private string IncrementVersion(string version)
        {
            if (string.IsNullOrEmpty(version))
                return "1.0.0";

            try
            {
                // 使用正则表达式匹配版本号中的数字部分
                var matches = System.Text.RegularExpressions.Regex.Matches(version, @"\d+");
                if (matches.Count > 0)
                {
                    // 获取最后一个数字
                    var lastMatch = matches[matches.Count - 1];
                    var lastNumber = int.Parse(lastMatch.Value);
                    var incrementedNumber = lastNumber + 1;

                    // 替换最后一个数字
                    return version.Substring(0, lastMatch.Index) + incrementedNumber + version.Substring(lastMatch.Index + lastMatch.Length);
                }
            }
            catch (System.Exception)
            {
                // 如果解析失败，返回默认版本号
            }

            return version;
        }

        /// <summary>
        /// 刷新DLCAsset列表
        /// </summary>
        private void RefreshDLCAssets()
        {
            _dlcAssets.Clear();
            _dlcSelection.Clear();

            // 在主工程中查找DLCAsset文件
            var mainProjectAssets = FindDLCAssetsInDirectory("Assets");
            foreach (var assetPath in mainProjectAssets)
            {
                var dlcInfo = CreateDLCAssetInfo(assetPath, "Main Project");
                if (dlcInfo != null)
                {
                    _dlcAssets.Add(dlcInfo);
                    _dlcSelection[dlcInfo.DLCName] = EditorPrefs.GetBool($"CallDlcAsset_Selection_{dlcInfo.DLCName}", false);
                }
            }

            // 在Packages中查找DLCAsset文件
            var packageAssets = FindDLCAssetsInDirectory("Packages");
            foreach (var assetPath in packageAssets)
            {
                var dlcInfo = CreateDLCAssetInfo(assetPath, "Package");
                if (dlcInfo != null)
                {
                    _dlcAssets.Add(dlcInfo);
                    _dlcSelection[dlcInfo.DLCName] = EditorPrefs.GetBool($"CallDlcAsset_Selection_{dlcInfo.DLCName}", false);
                }
            }

            // 按DLC名称排序
            _dlcAssets = _dlcAssets.OrderBy(d => d.DLCName).ToList();
        }

        /// <summary>
        /// 在指定目录中查找DLCAsset文件
        /// </summary>
        private List<string> FindDLCAssetsInDirectory(string directory)
        {
            var dlcAssets = new List<string>();

            try
            {
                // 使用AssetDatabase查找所有DLCAsset.asset文件
                var allAssets = AssetDatabase.FindAssets("t:DLCAsset");
                foreach (var guid in allAssets)
                {
                    var assetPath = AssetDatabase.GUIDToAssetPath(guid);
                    if (assetPath.StartsWith(directory + "/"))
                    {
                        dlcAssets.Add(assetPath);
                    }
                }
            }
            catch (System.Exception ex)
            {
                Debug.LogWarning($"在目录 {directory} 中查找DLCAsset文件失败: {ex.Message}");
            }

            return dlcAssets;
        }

        /// <summary>
        /// 创建DLCAsset信息
        /// </summary>
        private DLCAssetInfo CreateDLCAssetInfo(string assetPath, string sourceType)
        {
            try
            {
                // 加载DLCAsset文件
                var dlcAsset = AssetDatabase.LoadAssetAtPath<ScriptableObject>(assetPath);
                if (dlcAsset == null)
                    return null;

                // 使用反射获取DLCAsset的属性
                var dlcName = GetSerializedPropertyValue(dlcAsset, "DLCName");
                var dlcVersion = GetSerializedPropertyValue(dlcAsset, "DLCVersion");
                var dlcDesc = GetSerializedPropertyValue(dlcAsset, "DLCDesc");

                if (string.IsNullOrEmpty(dlcName))
                    return null;

                var dlcInfo = new DLCAssetInfo
                {
                    DLCName = dlcName,
                    DLCVersion = dlcVersion ?? "1.0.0",
                    DLCDesc = dlcDesc ?? "",
                    AssetPath = assetPath,
                    SourceType = sourceType
                };

                // 查找与DLCAsset同源的Addressable Groups
                dlcInfo.Groups = FindRelatedAddressableGroups(dlcInfo);

                return dlcInfo;
            }
            catch (Exception ex)
            {
                Debug.LogWarning($"创建DLCAsset信息失败 {assetPath}: {ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 使用反射获取序列化属性值
        /// </summary>
        private string GetSerializedPropertyValue(ScriptableObject obj, string propertyName)
        {
            try
            {
                var serializedObject = new SerializedObject(obj);
                var property = serializedObject.FindProperty(propertyName);
                return property?.stringValue;
            }
            catch
            {
                return null;
            }
        }
        private void SetSerializedPropertyValue(ScriptableObject obj, string propertyName, string value)
        {
            try
            {
                var serializedObject = new SerializedObject(obj);
                var property = serializedObject.FindProperty(propertyName);
                property.stringValue = value;
                serializedObject.ApplyModifiedProperties();
                EditorUtility.SetDirty(obj);
                AssetDatabase.SaveAssets();
            }
            catch { }
        }

        /// <summary>
        /// 查找与DLCAsset同源的Addressable Groups
        /// </summary>
        private List<AddressableAssetGroup> FindRelatedAddressableGroups(DLCAssetInfo dlcInfo)
        {
            var relatedGroups = new List<AddressableAssetGroup>();
            var settings = AddressableAssetSettingsDefaultObject.Settings;

            try
            {
                // 获取DLCAsset文件所在的目录
                var dlcDirectory = Path.GetDirectoryName(dlcInfo.AssetPath);

                foreach (var group in settings.groups)
                {
                    if (group == null) continue;

                    // 获取组所在的路径
                    var groupPath = AssetDatabase.GetAssetPath(group);
                    if (string.IsNullOrEmpty(groupPath)) continue;

                    // 检查组是否与DLCAsset同源
                    if (IsGroupRelatedToDLC(groupPath, dlcDirectory, dlcInfo.SourceType))
                    {
                        relatedGroups.Add(group);
                    }
                }
            }
            catch (System.Exception ex)
            {
                Debug.LogWarning($"查找与DLC {dlcInfo.DLCName} 相关的Addressable Groups失败: {ex.Message}");
            }

            return relatedGroups;
        }

        /// <summary>
        /// 检查组是否与DLCAsset同源
        /// </summary>
        private bool IsGroupRelatedToDLC(string groupPath, string dlcDirectory, string sourceType)
        {
            if (sourceType == "Main Project")
            {
                // 主工程：组路径必须在Assets/目录下
                return groupPath.StartsWith("Assets/");
            }
            else if (sourceType == "Package")
            {
                // 包：组路径与DLCAsset路径在同一包内
                var packageName = ExtractPackageName(dlcDirectory);
                var groupPackageName = ExtractPackageName(groupPath);
                return packageName == groupPackageName;
            }

            return false;
        }

        /// <summary>
        /// 从路径中提取包名
        /// </summary>
        private string ExtractPackageName(string path)
        {
            path = path.Replace("\\", "/");
            if (path.Contains("Packages/"))
            {
                int startIndex = path.IndexOf("Packages/") + 9; // "Packages/".Length
                int endIndex = path.IndexOf('/', startIndex);
                if (endIndex > startIndex)
                {
                    return path.Substring(startIndex, endIndex - startIndex);
                }
            }
            return "";
        }



        /// <summary>
        /// 选中或取消选中搜索的DLC
        /// </summary>
        private void SelectSearchedDLCs(bool select)
        {
            foreach (var dlc in _dlcAssets)
            {
                // 如果没有搜索文本，则处理所有DLC
                if (string.IsNullOrEmpty(_searchText) ||
                    dlc.DLCName.ToLower().Contains(_searchText.ToLower()) ||
                    dlc.DLCDesc.ToLower().Contains(_searchText.ToLower()))
                {
                    _dlcSelection[dlc.DLCName] = select;
                }
            }
        }

        /// <summary>
        /// 构建选中的DLC
        /// </summary>
        private void BuildSelectedDLCs()
        {
            var selectedDLCs = _dlcAssets.Where(d => _dlcSelection[d.DLCName]).ToList();

            if (selectedDLCs.Count == 0)
            {
                EditorUtility.DisplayDialog("提示", "请至少选择一个DLC进行构建。", "确定");
                return;
            }

            _isBuilding = true;
            Repaint();

            // 保存选择状态
            foreach (var kvp in _dlcSelection)
                EditorPrefs.SetBool($"CallDlcAsset_Selection_{kvp.Key}", kvp.Value);

            try
            {
                // 按AddressableAssetSettings分组构建
                var buildResults = new List<(string dlcName, bool success)>();

                foreach (var dlc in selectedDLCs)
                {
                    if (dlc.Groups.Count == 0)
                    {
                        Log($"DLC {dlc.DLCName} 没有找到相关的Addressable Groups，跳过构建");
                        buildResults.Add((dlc.DLCName, false));
                        continue;
                    }

                    Log($"开始构建 DLC {dlc.DLCName}，共 {dlc.Groups.Count} 个组...");

                    // 使用对应的AddressableAssetSettings进行构建
                    bool buildSuccess = BuildAddressablesContent(dlc);
                    buildResults.Add((dlc.DLCName, buildSuccess));

                    if (buildSuccess)
                    {
                        Log($"成功构建 DLC {dlc.DLCName}！");
                    }
                    else
                    {
                        Log($"构建 DLC {dlc.DLCName} 失败");
                    }
                }

                // 显示构建结果汇总
                int successCount = buildResults.Count(r => r.success);
                int totalCount = buildResults.Count;

                if (successCount == totalCount)
                {
                    EditorUtility.DisplayDialog("成功", $"成功构建所有 {successCount} 个DLC！", "确定");
                }
                else if (successCount > 0)
                {
                    EditorUtility.DisplayDialog("部分成功", $"成功构建 {successCount} 个DLC，失败 {totalCount - successCount} 个。请查看控制台日志获取详细信息。", "确定");
                }
                else
                {
                    EditorUtility.DisplayDialog("失败", "所有DLC构建失败，请查看控制台日志获取详细信息。", "确定");
                }
            }
            catch (System.Exception ex)
            {
                Log($"构建异常: {ex.Message}\n{ex.StackTrace}");
                EditorUtility.DisplayDialog("异常", $"构建过程中发生异常：{ex.Message}", "确定");
            }
            finally
            {
                _isBuilding = false;
                Repaint();
            }
        }



        /// <summary>
        /// 构建Addressables内容
        /// </summary>
        private bool BuildAddressablesContent(DLCAssetInfo Info)
        {
            try
            {
                var settings = AddressableAssetSettingsDefaultObject.Settings;

                string path = Path.Combine(DBService.Config.DBServiceConfig.LocalABRoot, Info.DLCName);
                // DLC 构建输出路径
                string BuildPath = "[DBService.Config.DBServiceConfig.LocalABRoot]" + $"/{Info.DLCName}";
                string LoadPath = "{DBService.Config.DBServiceConfig.LocalABRoot}" + $"/{Info.DLCName}";

                // 让 catalog.json、hash、bundle 都指向 DLC 文件夹
                settings.BuildRemoteCatalog = true;
                settings.RemoteCatalogBuildPath = new ProfileValueReference();
                settings.RemoteCatalogBuildPath.SetVariableByName(settings, BuildPath);
                settings.RemoteCatalogLoadPath = new ProfileValueReference();
                settings.RemoteCatalogLoadPath.SetVariableByName(settings, LoadPath);

                var defaultGroup = settings.DefaultGroup;
                var defschema = defaultGroup.GetSchema<BundledAssetGroupSchema>();
                defschema.BundleNaming = BundledAssetGroupSchema.BundleNamingStyle.NoHash;

                defschema.IncludeInBuild = true;


                // 1️⃣ 获取当前变量名（通常是 LocalBuildPath / LocalLoadPath）
                string buildVarName = defschema.BuildPath.GetName(settings);
                string loadVarName = defschema.LoadPath.GetName(settings);

                string originalBuildPath = settings.profileSettings.GetValueByName(settings.activeProfileId, buildVarName);
                string originalLoadPath = settings.profileSettings.GetValueByName(settings.activeProfileId, loadVarName);


                // 2️⃣ 修改 Profile 中的实际路径值
                settings.profileSettings.SetValue(settings.activeProfileId, buildVarName, BuildPath);
                settings.profileSettings.SetValue(settings.activeProfileId, loadVarName, LoadPath);

                // 3️⃣ 强制重新解析（刷新 ProfileValueReference 内缓存）
                defschema.BuildPath.SetVariableByName(settings, buildVarName);
                defschema.LoadPath.SetVariableByName(settings, loadVarName);

                // 4️⃣ 保存修改
                EditorUtility.SetDirty(settings);
                EditorUtility.SetDirty(defschema);
                EditorUtility.SetDirty(defaultGroup);
                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();


                // 暂存 Include 状态
                var originalStates = new Dictionary<AddressableAssetGroup, bool>();

                foreach (var group in settings.groups)
                {
                    if (group == null) continue;

                    var schema = group.GetSchema<BundledAssetGroupSchema>();
                    if (schema == null) continue;

                    originalStates[group] = schema.IncludeInBuild;
                    schema.IncludeInBuild = Info.Groups.Contains(group);

                    // 确保每个组都输出到当前 DLC 目录
                    schema.BuildPath.SetVariableByName(settings, BuildPath);
                    schema.LoadPath.SetVariableByName(settings, LoadPath);
                }

                // 强制 builtin shader bundle 跟随路径
                settings.OverridePlayerVersion = $"{Info.DLCName.ToLower()}_shaders";
                settings.ShaderBundleNaming = ShaderBundleNaming.Custom;
                settings.ShaderBundleCustomNaming = $"{Info.DLCName.ToLower()}_shaders_{PlayerSettings.bundleVersion}";

                settings.profileSettings.SetValue(settings.activeProfileId, AddressableAssetSettings.kRemoteBuildPath, BuildPath);
                settings.profileSettings.SetValue(settings.activeProfileId, AddressableAssetSettings.kRemoteLoadPath, LoadPath);

                // 构建
                AddressableAssetSettings.BuildPlayerContent(out AddressablesPlayerBuildResult result);

                // 2️⃣ 修改 Profile 中的实际路径值
                settings.profileSettings.SetValue(settings.activeProfileId, buildVarName, originalBuildPath);
                settings.profileSettings.SetValue(settings.activeProfileId, loadVarName, originalLoadPath);

                // 3️⃣ 强制重新解析（刷新 ProfileValueReference 内缓存）
                defschema.BuildPath.SetVariableByName(settings, buildVarName);
                defschema.LoadPath.SetVariableByName(settings, loadVarName);

                EditorUtility.SetDirty(settings);
                EditorUtility.SetDirty(defschema);
                EditorUtility.SetDirty(defaultGroup);
                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();

                BuildDLCInfoJson(path, Info);

                // 恢复 Include 状态
                foreach (var kvp in originalStates)
                {
                    var schema = kvp.Key.GetSchema<BundledAssetGroupSchema>();
                    if (schema != null)
                        schema.IncludeInBuild = kvp.Value;
                }

                if (result != null && string.IsNullOrEmpty(result.Error))
                {
                    Log($"✅ DLC {Info.DLCName} 构建成功，开始复制 Catalog...");

                    string outputPath = GetAddressablesOutputPath(settings);
                    Log($"当前 Addressables 实际构建路径为: {outputPath}");

                    return true;
                }
                else
                {
                    Log($"❌ 构建失败: {result?.Error}");
                    return false;
                }
            }
            catch (System.Exception ex)
            {
                Log($"构建异常: {ex.Message}\n{ex.StackTrace}");
                return false;
            }
        }


        /// <summary>
        /// 获取 Addressables 当前配置下的实际构建输出路径（包含 catalog.json、hash、bundle）
        /// </summary>
        private string GetAddressablesOutputPath(AddressableAssetSettings settings)
        {
            // 获取当前活跃的 profile
            var profileId = settings.activeProfileId;

            // 取 RemoteCatalogBuildPath 或默认构建路径
            string catalogBuildPath = null;

            if (settings.BuildRemoteCatalog && settings.RemoteCatalogBuildPath != null)
            {
                catalogBuildPath = settings.profileSettings.EvaluateString(profileId, settings.RemoteCatalogBuildPath.GetValue(settings));
            }
            else
            {
                // 没开远程 catalog 时，用默认 build 路径（通常是 ServerData/...）
                var defaultSchema = settings.groups
                    .Select(g => g?.GetSchema<BundledAssetGroupSchema>())
                    .FirstOrDefault(s => s != null);
                if (defaultSchema != null)
                {
                    catalogBuildPath = settings.profileSettings.EvaluateString(profileId, defaultSchema.BuildPath.GetValue(settings));
                }
            }

            return catalogBuildPath;
        }

        /// <summary>
        /// DLC信息文件
        /// </summary>
        void BuildDLCInfoJson(string buildPath, DLCAssetInfo Info)
        {
            ExternalContentInfo info = new ExternalContentInfo
            {
                name = Info.DLCName,
                version = Info.DLCVersion,
                description = Info.DLCDesc,
                companyName = Application.companyName,
                productName = Application.productName,
                date = DateTime.Now
            };
            var path = Path.Combine(buildPath, "info.json");
            if (!string.IsNullOrEmpty(path))
            {
                using var _s = new StreamWriter(path);
                _s.Write(JToken.FromObject(info).ToString());
                _s.Flush();
            }

            var assetPath = Info.AssetPath;
            var dlcAsset = AssetDatabase.LoadAssetAtPath<ScriptableObject>(assetPath);
            if (dlcAsset == null)
                return;

            SetSerializedPropertyValue(dlcAsset, "DLCName", Info.DLCName);
            SetSerializedPropertyValue(dlcAsset, "DLCVersion", Info.DLCVersion);
            SetSerializedPropertyValue(dlcAsset, "DLCDesc", Info.DLCDesc);

            AssetDatabase.Refresh();
        }


        /// <summary>
        /// 记录构建日志
        /// </summary>
        private void Log(string message)
        {
            WriteLog(message, "", Debug.Log);
        }

        private void LogError(string message)
        {
            WriteLog(message, "  Error  ", Debug.LogError);
        }

        private void LogWarning(string message)
        {
            WriteLog(message, "  Warning  ", Debug.LogWarning);
        }

        private void WriteLog(string message, string logType, Action<string> logMethod)
        {
            string log = $"[{System.DateTime.Now:HH:mm:ss}]{logType} {message}\n";
            logMethod($"[CallDlcAsset] {message}");
            try { File.AppendAllText("Library/AddressableBuildLogs.txt", log); }
            catch (Exception ex) { Debug.LogWarning($"[CallDlcAsset] 无法写入日志文件: {ex.Message}"); }
        }
    }
}
#endif